import 'package:flutter/material.dart';
import 'package:flutter_bsbdj/data_base/data_base.dart';
import 'package:flutter_bsbdj/utils/constant.dart';
import 'package:flutter_bsbdj/utils/http_util.dart';
import 'package:flutter_bsbdj/bean/novel_info.dart';
import 'package:flutter_bsbdj/utils/widget_views.dart';
import 'package:flutter_bsbdj/data_base/novel_table.dart';
import 'novel_detail.dart';
import 'novel_search.dart';

class NovelIndex extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return IndexWidget();
  }
}

class IndexWidget extends State<NovelIndex> {
  int _currentIndex = 0;
  String title = "小说列表";
  ReadHistory readHistory;
  NovelRecommend recommend;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    readHistory = ReadHistory((value) {
      if (value == "startReader") {
        setState(() {
          _currentIndex = 0;
        });
      }
    });
    recommend = NovelRecommend();

  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.search,
              color: Colors.white,
            ),
            onPressed: () {
              Navigator.of(context)
                  .push(MaterialPageRoute(builder: (context) => NovelSearch()));
            },
          ),
        ],
      ),
      body: IndexedStack(
        children: <Widget>[
          recommend,
          readHistory,
        ],
        index: _currentIndex,
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(
            icon: Container(
              height: 25,
              width: 25,
              child: Image.asset("images/recommend_nom.png"),
            ),
            activeIcon: Container(
              height: 25,
              width: 25,
              child: Image.asset("images/recommend_sp.png"),
            ),
            title: Text(
              "推荐",
              style: TextStyle(
                  color: _currentIndex == 0
                      ? Color(0xffd81e06)
                      : Color(0xffbfbfbf)),
            ),
          ),
          BottomNavigationBarItem(
            icon: Container(
              width: 25,
              height: 25,
              child: Image.asset("images/hostory_nom.png"),
            ),
            activeIcon: Container(
              width: 25,
              height: 25,
              child: Image.asset("images/hostory_sp.png"),
            ),
            title: Text(
              "阅读记录",
              style: TextStyle(
                  color: _currentIndex == 1
                      ? Color(0xffd81e06)
                      : Color(0xffbfbfbf)),
            ),
          ),
        ],
        currentIndex: _currentIndex,
        onTap: (value) {
          setState(() {
            _currentIndex = value;
            if (value == 0) {
              title = "小说列表";
            } else {
              title = "阅读记录";
              readHistory.refresh();
            }
          });
        },
        iconSize: 4,
      ),
    );
  }
}

//推荐
class NovelRecommend extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return RecommendWidgets();
  }
}

class RecommendWidgets extends State<NovelRecommend> {
  List<NovelItem> _novellist = [];
  Constant _constant;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getNovelList();
    _constant=Constant.getInstance();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Container(
          child: RefreshIndicator(
              child: ListView.builder(
                itemCount: _novellist.length,
                itemBuilder: (content, index) {
                  return _novelItem(_novellist[index]);
                },
              ),
              onRefresh: _onRefresh)),
    );
  }

  Future<Null> _onRefresh() async {
    await _getNovelList();
    return null;
  }

  Widget _novelItem(NovelItem item) {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.all(5),
        padding: EdgeInsets.all(5),
        color: _constant.getItemColor(),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              height: 100,
              child: Row(
                children: <Widget>[
                  Container(
                    height: 100,
                    width: 80,
                    margin: EdgeInsets.only(
                      right: 10,
                    ),
                    child:
                        WidgetViews.getInstance().cachedImage(item.book_cover),
                  ),
                  Expanded(
                      child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: Text(
                          item.bookname,
                          style: TextStyle(
                              fontSize: 15,
                              color: _constant.getTheme()?Colors.black54:Colors.white,
                              fontWeight: FontWeight.bold),
                        ),
                      ),
                      Expanded(
                        child: Row(
                          children: <Widget>[
                            Text(
                              "${item.author_name}   ",
                              style:
                                  TextStyle(fontSize: 13, color: Colors.grey),
                            ),
                            Text(
                              "${item.stat_name}   ",
                              style:
                                  TextStyle(fontSize: 12, color: Colors.green),
                            ),
                            Text(
                              item.class_name,
                              style: TextStyle(
                                  fontSize: 12, color: Colors.deepOrange),
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        child: Text(item.tag.toString()),
                      ),
                      Expanded(
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              child: Text("点击量:${item.num_click}"),
                            ),
                            Expanded(
                              child: Text("分享:${item.recommend_num}"),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ))
                ],
              ),
              margin: EdgeInsets.only(bottom: 5),
            ),
            Text(item.book_info),
          ],
        ),
      ),
      onTap: () {
        _insertData(item);
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => NovelReader(
                item.bookname, item.bid, item.chapterid_first, true)));
      },
    );
  }

  void _insertData(NovelItem item) async {
    var t = await NovelTable.getInstance()
        .insertBook(
            0,
            item.author,
            item.author_name,
            item.bookname,
            item.bid,
            item.chapterid_first,
            item.book_cover,
            item.class_name,
            item.book_info.length > 25
                ? item.book_info.substring(0, 25).replaceAll("\n", "")
                : item.book_info.replaceAll("\n", ""))
        .then((value) {
      print("*********  $value");
    });
  }

  void _getNovelList() async {
    var t = await HttpUtil.getInstance().get("novelApi").then((value) {
      try {
        NovelInfo novelInfo = NovelInfo.fromJson(value.data);
        print(novelInfo);
        setState(() {
          _novellist = novelInfo.data;
        });
      } catch (e) {}
    });
  }
}

//阅读历史
class ReadHistory extends StatefulWidget {
  Function startReader;

  ReadHistory(this.startReader);

  HistoryWidget historyWidget = HistoryWidget();

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return historyWidget;
  }

  void refresh() {
    historyWidget.refresh();
  }
}

class HistoryWidget extends State<ReadHistory> {
  List<NovelTableInfo> _history;
  bool _isEdit = false;
  List<int> _checkIndex = [];
  Constant _constant;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getNovelHustory();
    _constant=Constant.getInstance();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Container(
        child: (_history == null || _history.length == 0)
            ? Container(
                alignment: Alignment.center,
                child: GestureDetector(
                  child: Text("无阅读记录，点击开始阅读..."),
                  onTap: () {
                    widget.startReader("startReader");
                  },
                ),
              )
            : Container(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Expanded(
                        child: ListView.builder(
                            itemCount: _history.length,
                            itemBuilder: (content, index) {
                              NovelTableInfo item = _history[index];
                              return GestureDetector(
                                child: Container(
                                  height: 110,
                                  color: _constant.getItemColor(),
                                  margin: EdgeInsets.all(5),
                                  padding: EdgeInsets.all(5),
                                  child: Row(
                                    children: <Widget>[
                                      _isEdit
                                          ? Container(
                                              alignment: Alignment.center,
                                              width: 30,
                                              child: IconButton(
                                                  icon: _checkIndex
                                                          .contains(item.id)
                                                      ? Icon(
                                                          Icons.check_circle,
                                                          color:
                                                              Colors.blueAccent,
                                                        )
                                                      : Icon(
                                                          Icons
                                                              .radio_button_unchecked,
                                                          color: Colors.grey,
                                                        ),
                                                  onPressed: () {
                                                    if (_checkIndex
                                                        .contains(item.id)) {
                                                      _checkIndex
                                                          .remove(item.id);
                                                    } else {
                                                      _checkIndex.add(item.id);
                                                    }
                                                    setState(() {});
                                                  }),
                                            )
                                          : Container(
                                              width: 0,
                                            ),
                                      Container(
                                        width: 80,
                                        child: WidgetViews.getInstance()
                                            .cachedImage(item.bookCover,
                                                function: () {
                                          _historyItemClick(item);
                                        }),
                                      ),
                                      Expanded(
                                          child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: <Widget>[
                                          Expanded(
                                              child: Text(
                                            item.bookName,
                                            style: TextStyle(
                                                fontSize: 15,
                                                color: _constant.getTheme()?Colors.black54:Colors.white,
                                                fontWeight: FontWeight.bold),
                                          )),
                                          Expanded(
                                              child: Text(
                                            "${item.authorName}",
                                            style: TextStyle(
                                                fontSize: 13,
                                                color: Colors.grey),
                                          )),
                                          Expanded(
                                            child: Text(item.bookInfo),
                                          )
                                        ],
                                      )),
                                    ],
                                  ),
                                ),
                                onLongPress: () {
                                  setState(() {
                                    _isEdit = true;
                                  });
                                },
                                onTap: () {
                                  _historyItemClick(item);
                                },
                              );
                            })),
                    _isEdit
                        ? Container(
                            alignment: Alignment.bottomRight,
                            height: 50,
                            child: Container(
                              child: Row(
                                children: <Widget>[
                                  Expanded(
                                      child: GestureDetector(
                                    child: Container(
                                      alignment: Alignment.center,
                                      child: Text("全选"),
                                    ),
                                    onTap: () {
                                      _checkIndex.clear();
                                      for (var t in _history) {
                                        _checkIndex.add(t.id);
                                      }
                                      setState(() {});
                                    },
                                  )),
                                  Expanded(
                                      child: GestureDetector(
                                    child: Container(
                                      alignment: Alignment.center,
                                      child: Text("删除"),
                                    ),
                                    onTap: () {
                                      if (_checkIndex.length > 0) {
                                        NovelTable.getInstance()
                                            .deleteByIds(_checkIndex, () {
                                          setState(() {
                                            _isEdit = false;
                                          });
                                          _getNovelHustory();
                                        });
                                      }
                                    },
                                  )),
                                  Expanded(
                                      child: GestureDetector(
                                    child: Container(
                                      alignment: Alignment.center,
                                      child: Text("取消"),
                                    ),
                                    onTap: () {
                                      setState(() {
                                        _isEdit = false;
                                        _checkIndex.clear();
                                      });
                                    },
                                  )),
                                ],
                              ),
                            ),
                          )
                        : Container(),
                  ],
                ),
              ),
      ),
    );
  }

  void _historyItemClick(NovelTableInfo item) {
    if (_isEdit) {
      if (_checkIndex.contains(item.id)) {
        _checkIndex.remove(item.id);
      } else {
        _checkIndex.add(item.id);
      }
      setState(() {});
    } else {
      Navigator.of(context).push(MaterialPageRoute(
          builder: (context) =>
              NovelReader(item.bookName, item.bid, item.cid, true)));
    }
  }

  void _getNovelHustory() async {
    await NovelTable.getInstance().getAllInfo().then((value) {
      setState(() {
        _history = value;
      });
    });
  }

  void refresh() {
    _getNovelHustory();
  }
}
